<?php

namespace Home\Controller;

use Common\Lib\Upload\ImgManager;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Think\Upload;

class UploadController extends CommonController
{
    /**
     * [attach 附件上传]
     */
    public function img()
    {
        $type = I('request.type', 'question_img', 'trim');
        if (!in_array($type, array(
                                   'question_img',
                                   'article_img',
                                   'kindeditor_img',
                                   'tag_img',
                                   'avatar_img',
                                   'category_img'
        ))) {
            return false;
        }
        if (IS_POST) {
            if (!empty($_FILES[$type]['name'])) {
                // 上传文件是否已存在UploadImg数据表中
                $UploadImg = D('UploadImg');
                $img       = $UploadImg->get_one_file($_FILES[$type]['tmp_name']);
                if (empty($img)) {
                    $maxSize          = 2097152;
                    $rootPath         = $this->get_rootpath($type);
                    $upload           = new Upload();// 实例化上传类
                    $upload->maxSize  = $maxSize;// 设置附件上传大小
                    $upload->autoSub  = false;
                    $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                    $upload->rootPath = $rootPath; // 设置附件上传根目录
                    $upload->savePath = date('Y/m/'); // 设置附件上传（子）目录
                    $upload->saveName = array('uniqid', '');

                    // 上传文件
                    $info = $upload->uploadOne($_FILES[$type]);
                    if (!$info) {// 上传错误提示错误信息
                        $ajax['status']  = 0;
                        $ajax['content'] = $upload->getError();
                        $this->ajaxReturn($ajax);
                        exit;
                    } else {// 上传成功
                        // 上传成功保存到UploadImg数据表
                        $img = $UploadImg->register($this->get_register_arr($info, $rootPath));
                        //生成缩略图
                        if ($this->get_savetype() === 'qiniu') {
                            $_file = $_FILES[$type]['tmp_name'];
                        } else {
                            $_file = $img['savepath'] . $img['savename'];
                        }
                        if ($type == 'question_img') {
                            $this->thumb($_file, array(100, 100), $img);
                        } else {
                            $this->thumb($_file, array(600, 600), $img);
                        }
                    }
                }
                // 根据上传图片注册ID生成需要返回的数据
                $imgManager                  = new ImgManager($img);
                $url                         = $imgManager->url();
                $ajax['status']              = 1;
                $ajax['content']['id']       = $img['id'];
                $ajax['content']['savename'] = $img['savename'];
                $ajax['content']['src']      = $url;

                // 编辑器返回格式
                if ($type == 'kindeditor_img') {
                    $kindeditor['error'] = 0;
                    $kindeditor['url']   = $url;
                    $this->ajaxReturn($kindeditor);
                }
                $this->ajaxReturn($ajax);

            } else {
                $ajax['status']  = 0;
                $ajax['content'] = "参数非法";
                $this->ajaxReturn($ajax);
            }
        }
    }

    /**
     * 生成缩略图 [支持本地和七牛云]
     * @param string $file 原图片路径
     * @param array  $size array('宽度', '高度')
     * @param array  $img  上传图片注册数据
     */
    private function thumb($file, $size, $img)
    {
        $thumb = $img['savepath'] . $img['savename'];
        $thumb = $thumb . '.thumb.' . substr(strrchr($thumb, '.'), 1);
        $image = new \Think\Image();
        $image->open($file);
        if (!is_dir(dirname($thumb))) mkdir(dirname($thumb), true);
        $image->thumb($size[0], $size[1])->save($thumb);

        if ($this->get_savetype() === 'qiniu') {
            vendor('Qiniu.autoload');
            $key     = $thumb;
            $auth    = new Auth(C('UPLOAD_TYPE_CONFIG.accessKey'), C('UPLOAD_TYPE_CONFIG.secretKey'));
            $expires = 3600;
            $policy  = null;
            $upToken = $auth->uploadToken(C('UPLOAD_TYPE_CONFIG.bucket'), null, $expires, $policy, true);
            // 初始化 UploadManager 对象并进行文件的上传。
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传。
            $uploadMgr->putFile($upToken, $key, $thumb);
            @unlink($thumb);
        }
    }

    /**
     * 根据类型获取上传图片根目录
     * @param string $type
     * @return string
     */
    private function get_rootpath($type)
    {
        switch ($type) {
            case 'question_img':
                $rootPath = C('YTATA_IMG_QUESTION_DIR');
                break;
            case 'article_img':
                $rootPath = C('YTATA_IMG_ARTICLE_DIR');
                break;
            case 'kindeditor_img':
                $rootPath = C('YTATA_IMG_ARTICLE_DIR');
                break;
            case 'category_img':
                $rootPath = C('YTATA_IMG_CATEGORY_DIR');
                break;
            case 'tag_img':
                $rootPath = C('YTATA_IMG_TAG_DIR');
                break;
            case 'avatar_img':
                $rootPath = C('YTATA_IMG_AVATAR_DIR');
                break;
            default:
                E('未知的上传图片内容类型');
                break;
        }
        return $rootPath;
    }

    /**
     * 获取保存方式 七牛云:qiniu 本地:local
     * @return string
     */
    private function get_savetype()
    {
        $type = strtolower(C('FILE_UPLOAD_TYPE'));

        return $type ?: 'local';
    }

    /**
     * 生成注册数据
     * 根据上传图片返回信息生成注册数据
     * @param array  $info
     * @param string $rootPath
     * @return array
     */
    private function get_register_arr(array $info, $rootPath)
    {
        return array('sha1'     => $info['sha1'],
                     'name'     => $info['name'],
                     'type'     => $info['type'],
                     'ext'      => $info['ext'],
                     'size'     => $info['size'],
                     'savename' => $info['savename'],
                     'savepath' => $rootPath . $info['savepath'],
                     'savetype' => $this->get_savetype()
        );
    }

    public function falsh()
    {
        $uid = session('ytata.uid');
        if (empty($uid)) {
            $ajax['status']  = 0;
            $ajax['content'] = "参数非法";
            $this->ajaxReturn($ajax);
        } else {
            $date        = date('Y/m/');
            $save_avatar = C('YTATA_IMG_AVATAR_DIR') . $date;//图片存储路径
            if (!is_dir($save_avatar)) {
                mkdir($save_avatar, 0777, true);
            }
            $savePicName = $uid . '.jpg';
            $filename    = $save_avatar . $savePicName;
            $pic         = base64_decode($_POST['pic1']);
            file_put_contents($filename, $pic);
            //生成缩略图
            $image = new \Think\Image();
            $image->open($filename)->thumb(150, 150)->save($filename);
            $picUrl = $filename;
            D('User')->edit_avatar($uid, $date . $savePicName);
            D('Task')->exe_user_avatar($uid);//完成上传头像任务
            $ajax['status'] = 1;
            $ajax['picUrl'] = $picUrl;
            $this->ajaxReturn($ajax);
        }

    }

}